package com.spsa.vista.util.excepciones;

import java.util.Iterator;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;


public class CustomExceptionHandler extends ExceptionHandlerWrapper{
	private ExceptionHandler wrapped;

	public CustomExceptionHandler(ExceptionHandler wrapped) {
		this.wrapped = wrapped;
	}
	
	@Override
	public ExceptionHandler getWrapped() {
		return wrapped;
	}
	
	@Override
	public void handle() throws FacesException {
		Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
		
		while(i.hasNext()) {
			ExceptionQueuedEvent event = i.next();
//			ExceptionQueuedEventContext context = (ExceptionQueuedEventContext)event.getSource();
//		
//			Throwable t = context.getException();
			FacesContext fc = FacesContext.getCurrentInstance();
			String viewId = "/error.xhtml";
			ViewHandler viewHandler = fc.getApplication().getViewHandler();
			fc.setViewRoot(viewHandler.createView(fc, viewId));
			fc.getPartialViewContext().setRenderAll(true);
			fc.renderResponse();
			
//			try {
//				NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
//				navigationHandler.handleNavigation(fc, null, "error?faces-redirect=true");
//				fc.renderResponse();
//			}
//			finally {
//				i.remove();
//			}
		}
		
		getWrapped().handle();
	}
}
